package time_20230818;

/**
 * @author lizhen
 * @date 2023/8/18 16:09
 */

import java.util.Arrays;

/**
 * 26.删除有序数组的重复项
 */
public class RemoveDuplicates {
    public static void main(String[] args) {
        int[] nums = new int[]{1, 1, 2};
        int k = removeDuplicates2(nums);
        System.out.println(Arrays.toString(nums));
        System.out.println(k);
    }

    public static int removeDuplicates(int[] nums) {
        if (nums.length == 0) {
            return 0;
        }

        int k = 0;
        for (int i = 0; i < nums.length; i++) {
            for (int j = i + 1; j < nums.length; j++) {
                if (nums[i] == nums[j]) {
                    k++;
                    break;
                }
            }
        }

        return nums.length - k;
    }

    public static int removeDuplicates2(int[] nums) {
        // 数组为空，直接返回0
        if (nums.length == 0) {
            return 0;
        }

        /*
            双指针：j指针表示不重复个数，第一个数一定是不重复的，从第二个开始计算
            i指针去寻找不重复的数字,找到就将不重复的数字赋值给j当前位置，然后j+1
         */
        int j = 1;
        for (int i = 1; i < nums.length; i++) {
            if (nums[i] != nums[i - 1])
                nums[j++] = nums[i];
        }

        return j;
    }

}
